package producerConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: javase
 * @description: 生产者消费者问题--lock版
 * @author: lld
 * @create: 2021-04-17 20:51
 **/
public class LockVersion {
    public static void main(String[] args) {
        Data2 number = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                number.increment();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                number.decrement();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                number.increment();
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                number.decrement();
            }
        }, "D").start();
    }
}

/**
 * @Description: 使用lock加锁解锁，condition的await(),signalAll()方法等待唤醒
 **/
class Data2 {
    private int num = 0;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

//判断等待，业务，唤醒
//    +1方法
    public void increment() {
        lock.lock();
        try {
            //等待 被消费
            while (num != 0) condition.await();
            num++;
            System.out.println(Thread.currentThread().getName() + ">>" + num);
//        唤醒 消费
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //    -1方法
    public void decrement() {
        lock.lock();
        try {
            //等待 生产
            while (num == 0) condition.await();
            num--;
            System.out.println(Thread.currentThread().getName() + ">>" + num);
//        唤醒
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
